<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<%
    // 检查是否已经有图书数据，如果没有则重定向到books路径
    if (request.getAttribute("books") == null && request.getAttribute("categories") == null) {
        response.sendRedirect("books");
        return;
    }
%>
<html>
<head>
    <title>万万书城 - 首页</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .header {
            background-color: #4CAF50;
            color: white;
            padding: 15px 0;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .header-container {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;
        }
        .logo {
            font-size: 24px;
            font-weight: bold;
        }
        .nav a {
            color: white;
            text-decoration: none;
            margin: 0 15px;
        }
        .nav a:hover {
            text-decoration: underline;
        }
        .content {
            max-width: 1200px;
            margin: 20px auto;
            padding: 0 20px;
        }
        .categories {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .categories h3 {
            margin-top: 0;
            color: #333;
        }
        .category-list {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        .category-item {
            padding: 5px 15px;
            background-color: #f0f0f0;
            border-radius: 20px;
            text-decoration: none;
            color: #333;
        }
        .category-item:hover {
            background-color: #4CAF50;
            color: white;
        }
        .books-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
        }
        .book-card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            padding: 20px;
            transition: transform 0.3s;
        }
        .book-card:hover {
            transform: translateY(-5px);
        }
        .book-title {
            font-size: 18px;
            font-weight: bold;
            margin: 0 0 10px 0;
            color: #333;
        }
        .book-author {
            color: #666;
            margin-bottom: 10px;
        }
        .book-price {
            color: #e74c3c;
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 15px;
        }
        .book-actions {
            display: flex;
            gap: 10px;
        }
        .btn {
            flex: 1;
            padding: 8px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            text-align: center;
        }
        .btn-primary {
            background-color: #4CAF50;
            color: white;
        }
        .btn-primary:hover {
            background-color: #45a049;
        }
        .btn-secondary {
            background-color: #2196F3;
            color: white;
        }
        .btn-secondary:hover {
            background-color: #1976D2;
        }
        .pagination {
            margin-top: 30px;
            text-align: center;
        }
        .pagination a {
            display: inline-block;
            padding: 8px 16px;
            margin: 0 4px;
            text-decoration: none;
            color: #333;
            background-color: white;
            border-radius: 4px;
        }
        .pagination a:hover {
            background-color: #4CAF50;
            color: white;
        }
        .pagination .active {
            background-color: #4CAF50;
            color: white;
        }
        .user-info {
            color: white;
        }
        .user-info a {
            color: white;
            margin-left: 10px;
        }
        
        /* 海报轮播样式 */
        .banner-carousel {
            margin: 0 auto 20px;
            max-width: 1200px;
            overflow: hidden;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            background-color: white;
        }
        
        .carousel-container {
            position: relative;
            width: 100%;
            max-width: 1200px;
            padding-bottom: 56.25%; /* 16:9 比例 */
            margin: 0 auto;
            overflow: hidden;
        }
        
        .carousel-slide {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .carousel-slide img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: opacity 0.5s ease;
        }
        
        .carousel-btn {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            background-color: rgba(0, 0, 0, 0.3); /* 半透明背景 */
            color: white;
            border: none;
            cursor: pointer;
            font-size: 30px;
            padding: 10px 15px;
            border-radius: 50%;
            transition: background-color 0.3s ease;
            z-index: 10;
        }
        
        .carousel-btn:hover {
            background-color: rgba(0, 0, 0, 0.5); /* 悬停时加深透明度 */
        }
        
        .prev-btn {
            left: 15px;
        }
        
        .next-btn {
            right: 15px;
        }
        
        .no-banner-text {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #666;
            font-size: 24px;
            display: none;
        }
    </style>
<script>
        // 当页面加载完成后，如果URL中包含keyword参数，则滚动到搜索结果区域
        window.addEventListener('DOMContentLoaded', function() {
            if (window.location.search.includes('keyword=')) {
                const searchResultHeader = document.getElementById('searchResultHeader');
                if (searchResultHeader) {
                    searchResultHeader.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
            }
        });
        
        // 海报轮播逻辑
        let currentSlide = 0;
        let slideInterval;
        const slides = [
            { url: './images/index_image/微信图片_20251022142655_5_46.jpg', alt: '海报1' },
            { url: './images/index_image/微信图片_20251022142656_6_46.jpg', alt: '海报2' },
            { url: './images/index_image/微信图片_20251022142657_7_46.jpg', alt: '海报3' },
            { url: './images/index_image/微信图片_20251022142658_8_46.jpg', alt: '海报4' },
            { url: './images/index_image/微信图片_20251022142659_9_46.jpg', alt: '海报5' },
            { url: './images/index_image/微信图片_20251022142659_10_46.jpg', alt: '海报6' }
        ];
        
        function changeSlide(n) {
            currentSlide = (currentSlide + n + slides.length) % slides.length;
            const img = document.getElementById('bannerImage');
            img.src = slides[currentSlide].url;
            img.alt = slides[currentSlide].alt;
            img.onload = hideNoBannerText;
            img.onerror = showNoBannerText;
        }
        
        // 自动轮播函数
        function startSlideInterval() {
            // 每5秒自动切换到下一张海报
            slideInterval = setInterval(() => {
                changeSlide(1);
            }, 5000);
        }
        
        // 停止自动轮播
        function stopSlideInterval() {
            clearInterval(slideInterval);
        }
        
        // 页面加载完成后开始自动轮播
        window.addEventListener('DOMContentLoaded', () => {
            startSlideInterval();
            
            // 获取轮播容器元素
            const carouselContainer = document.querySelector('.carousel-container');
            
            // 鼠标悬停时暂停自动轮播
            carouselContainer.addEventListener('mouseenter', stopSlideInterval);
            
            // 鼠标离开时恢复自动轮播
            carouselContainer.addEventListener('mouseleave', startSlideInterval);
        });
        
        function hideNoBannerText() {
            document.getElementById('noBannerText').style.display = 'none';
        }
        
        function showNoBannerText() {
            document.getElementById('noBannerText').style.display = 'block';
        }
        
        // 刷新推荐图书
        document.getElementById('refreshRecommendedBtn').addEventListener('click', function() {
            const recommendedContent = document.getElementById('recommendedContent');
            recommendedContent.innerHTML = '<div style="text-align: center; padding: 40px 0; color: #666;">加载中...</div>';
            
            // 发送请求获取新的推荐图书
            fetch('index?action=refreshRecommendedBooks')
                .then(response => response.text())
                .then(html => {
                    recommendedContent.innerHTML = html;
                })
                .catch(error => {
                    console.error('刷新推荐图书失败:', error);
                    recommendedContent.innerHTML = '<div style="text-align: center; padding: 40px 0; color: #666;">刷新失败，请稍后重试</div>';
                });
        });
    </script>
</head>
<body>
    <div class="header">
        <div class="header-container">
            <div class="logo">万万书城</div>
            <div class="nav">
                <a href="index.jsp">首页</a>
                <a href="cart">购物车</a>
                <a href="order?action=list">我的订单</a>
                <a href="userCenter">用户中心</a>
            </div>
            <div class="user-info">
                <% if (session.getAttribute("user") != null) {
                    com.wanwanbookstore.entity.User user = (com.wanwanbookstore.entity.User) session.getAttribute("user");
                    out.println(user.getUsername() + " <a href='logout'>退出</a>");
                } else {
                    out.println("<a href='login.jsp'>登录</a> <a href='register.jsp'>注册</a>");
                }
                %>
            </div>
        </div>
    </div>

    <div class="content">
        <!-- 搜索区域 -->
        <div style="text-align: right; margin-bottom: 20px;">
            <form action="books" method="get" style="display: inline-block; padding: 10px; background-color: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                <input type="text" name="keyword" placeholder="搜索图书..." style="padding: 8px; width: 300px; border: 1px solid #ddd; border-radius: 4px;">
                <button type="submit" style="padding: 8px 16px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer;">搜索</button>
            </form>
        </div>
        
        <!-- 海报轮播区域 -->
        <div class="banner-carousel">
            <div class="carousel-container">
                <button class="carousel-btn prev-btn" onclick="changeSlide(-1)">‹</button>
                <div class="carousel-slide">
                    <!-- 海报图片 -->
                    <img id="bannerImage" src="./images/index_image/微信图片_20251022142655_5_46.jpg" alt="海报1" onload="hideNoBannerText()" onerror="showNoBannerText()">
                    <div id="noBannerText" class="no-banner-text">无海报</div>
                </div>
                <button class="carousel-btn next-btn" onclick="changeSlide(1)">›</button>
            </div>
        </div>
        
        <!-- 推荐图书区域 -->
        <div class="recommended-books">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                <h3>推荐图书</h3>
                <button id="refreshRecommendedBtn" style="background: none; border: 1px solid #ccc; border-radius: 50%; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; cursor: pointer; font-size: 16px;">
                    ↻
                </button>
            </div>
            
            <div id="recommendedContent">
                <c:if test="${empty recommendedBooks || recommendedBooks.size() == 0}">
                    <div style="text-align: center; padding: 40px 0; color: #666; background-color: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                        尊敬的用户，新功能敬请期待，可以先逛一逛哦
                    </div>
                </c:if>
                
                <c:if test="${not empty recommendedBooks && recommendedBooks.size() > 0}">
                    <div class="books-grid">
                        <c:forEach items="${recommendedBooks}" var="book">
                            <div class="book-card">
                                <div class="book-image">
                                    <a href="bookDetail?id=${book.id}">
                                        <img src="<%= "images/书籍图片jpg/" + pageContext.getAttribute("book").getClass().getMethod("getTitle").invoke(pageContext.getAttribute("book")) + ", " + pageContext.getAttribute("book").getClass().getMethod("getAuthor").invoke(pageContext.getAttribute("book")) + ".jpg" %>" alt="${book.title}" width="150" height="200" onerror="this.src='https://via.placeholder.com/150x200?text=No+Image'">
                                    </a>
                                </div>
                                <h4 class="book-title">
                                    <a href="bookDetail?id=${book.id}" style="color: #333; text-decoration: none;">${book.title}</a>
                                </h4>
                                <div class="book-author">作者：${book.author}</div>
                                <div class="book-price">¥${book.price}</div>
                                <div class="book-actions" style="display: flex; flex-direction: column; gap: 8px;">
                                    <form action="cart" method="post" style="display: inline; width: 100%;">
                                        <input type="hidden" name="action" value="add">
                                        <input type="hidden" name="bookId" value="${book.id}">
                                        <input type="hidden" name="quantity" value="1">
                                        <button type="submit" class="btn btn-secondary" style="width: 100%;">加入购物车</button>
                                    </form>
                                    <form action="cart" method="post" style="display: flex; align-items: center; gap: 8px; width: 100%;">
                                        <input type="hidden" name="action" value="add">
                                        <input type="hidden" name="bookId" value="${book.id}">
                                        <input type="hidden" name="type" value="direct">
                                        <button type="submit" class="btn btn-primary" style="flex: 1;">立即购买</button>
                                        <div style="display: flex; align-items: center; gap: 5px;">
                                            <span>数量：</span>
                                            <input type="number" name="quantity" value="1" min="1" max="${book.stock}" style="width: 50px; text-align: center; padding: 5px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;">
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </c:forEach>
                    </div>
                </c:if>
            </div>
        </div>
        
        <div class="categories">
            <h3>图书分类</h3>
            <div class="category-list">
                <a href="books" class="category-item">全部图书</a>
                <c:forEach items="${categories}" var="category">
                    <a href="books?category=${category}" class="category-item ${currentCategory == category ? 'active' : ''}">${category}</a>
                </c:forEach>
            </div>
        </div>
        
        <!-- 搜索结果标题 -->
        <c:if test="${not empty keyword}">
            <div id="searchResultHeader" style="margin-bottom: 20px; padding: 10px; background-color: #f0f8ff; border-radius: 8px;">
                <h3>搜索结果: "${keyword}"</h3>
            </div>
        </c:if>

        <div class="books-grid">
            <c:forEach items="${books}" var="book">
                <div class="book-card">
                    <div class="book-image">
                        <%-- 这里可以放图书封面图片，如果没有可以用默认图片或文本占位 --%>
                        <a href="bookDetail?id=${book.id}">
                            <img src="<%= "images/书籍图片jpg/" + pageContext.getAttribute("book").getClass().getMethod("getTitle").invoke(pageContext.getAttribute("book")) + ", " + pageContext.getAttribute("book").getClass().getMethod("getAuthor").invoke(pageContext.getAttribute("book")) + ".jpg" %>" alt="${book.title}" width="150" height="200" onerror="this.src='https://via.placeholder.com/150x200?text=No+Image'">
                        </a>
                    </div>
                    <h4 class="book-title">
                        <a href="bookDetail?id=${book.id}" style="color: #333; text-decoration: none;">${book.title}</a>
                    </h4>
                    <div class="book-author">作者：${book.author}</div>
                    <div class="book-price">¥${book.price}</div>
                    <div class="book-actions">
                        <form action="cart" method="post" style="display: inline; flex: 1;">
                            <input type="hidden" name="action" value="add">
                            <input type="hidden" name="bookId" value="${book.id}">
                            <input type="hidden" name="quantity" value="1">
                            <button type="submit" class="btn btn-secondary">加入购物车</button>
                        </form>
                        <form action="cart" method="post" style="display: inline; flex: 1; display: flex; flex-direction: column; gap: 5px;">
                            <input type="hidden" name="action" value="add">
                            <input type="hidden" name="bookId" value="${book.id}">
                            <input type="number" name="quantity" value="1" min="1" max="${book.stock}" style="width: 100%; text-align: center;">
                            <input type="hidden" name="type" value="direct">
                            <button type="submit" class="btn btn-primary">立即购买</button>
                        </form>
                    </div>
                </div>
            </c:forEach>
        </div>

        <div class="pagination">
            <c:if test="${currentPage > 1}">
                <a href="books?page=${currentPage - 1}&category=${currentCategory}" class="pagination-link">上一页</a>
            </c:if>
            <c:forEach begin="1" end="${totalPages}" var="i">
                <a href="books?page=${i}&category=${currentCategory}" class="${i == currentPage ? 'active' : ''} pagination-link">${i}</a>
            </c:forEach>
            <c:if test="${currentPage < totalPages}">
                <a href="books?page=${currentPage + 1}&category=${currentCategory}" class="pagination-link">下一页</a>
            </c:if>
        </div>
    </div>
    
    <!-- 回到顶部按钮 -->
    <button id="backToTopBtn" style="position: fixed; bottom: 30px; right: 30px; background-color: #4CAF50; color: white; border: none; border-radius: 50%; width: 50px; height: 50px; font-size: 20px; cursor: pointer; display: none; z-index: 1000; box-shadow: 0 2px 4px rgba(0,0,0,0.2);">↑</button>
    
    <script>
        // 为换一换按钮添加点击事件，实现页面刷新功能
        document.getElementById('refreshRecommendedBtn').onclick = function() {
            location.reload();
        };
        
        // 回到顶部按钮功能
        const backToTopBtn = document.getElementById('backToTopBtn');
        
        // 监听滚动事件，显示/隐藏回到顶部按钮
        window.addEventListener('scroll', function() {
            if (window.pageYOffset > 300) {
                backToTopBtn.style.display = 'block';
            } else {
                backToTopBtn.style.display = 'none';
            }
        });
        
        // 点击回到顶部
        backToTopBtn.addEventListener('click', function() {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });
        
        // 保存滚动位置到localStorage，以便分页后恢复
        window.addEventListener('beforeunload', function() {
            localStorage.setItem('scrollPosition', window.scrollY);
        });
        
        // 页面加载时恢复滚动位置并处理搜索结果焦点
        window.addEventListener('DOMContentLoaded', function() {
            // 首先恢复滚动位置
            const scrollPosition = localStorage.getItem('scrollPosition');
            if (scrollPosition) {
                window.scrollTo(0, parseInt(scrollPosition));
                localStorage.removeItem('scrollPosition');
            }
            
            // 然后检查是否有搜索关键词，如果有则聚焦到搜索结果标题
            <c:if test="${not empty keyword}">
                setTimeout(function() {
                    const searchResultHeader = document.getElementById('searchResultHeader');
                    if (searchResultHeader) {
                        // 使用自定义平滑滚动代替scrollIntoView
                        const targetPosition = searchResultHeader.getBoundingClientRect().top + window.pageYOffset - 50; // 50px的顶部偏移量
                        const startPosition = window.pageYOffset;
                        const distance = targetPosition - startPosition;
                        const duration = 500; // 滚动持续时间（毫秒）
                        let startTime = null;
                        
                        function animation(currentTime) {
                            if (startTime === null) startTime = currentTime;
                            const timeElapsed = currentTime - startTime;
                            const run = ease(timeElapsed, startPosition, distance, duration);
                            window.scrollTo(0, run);
                            if (timeElapsed < duration) requestAnimationFrame(animation);
                            else {
                                // 滚动完成后设置焦点
                                searchResultHeader.setAttribute('tabindex', '-1');
                                searchResultHeader.focus();
                            }
                        }
                        
                        // 缓动函数，使滚动更自然
                        function ease(t, b, c, d) {
                            t /= d;
                            return c * t * t + b;
                        }
                        
                        requestAnimationFrame(animation);
                    }
                }, 100);
            </c:if>
        });
    </script>
</body>
</html>